from util.DataQuery.hzflowOperation import hzflowOperation
from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM
from util.DataQuery.DbTools import DbTools
from util.DataQuery.FormDataDecorator import FormDataDecorator

from PageObject.write_equity import WriteCivilType, WriteLegalType, WriteVentureInvestment

# # # # # # # # # # # # #              填写注册登记表                       3       # # # # # # # #   unfinished----guquanjiegou                 # # # #
from util.g import g
from util.sys_dict import saleIncome, listedType


class WriteRegistrationForm():
    form_btn_loc = (By.LINK_TEXT, '注册登记表')
    title_loc = (By.CSS_SELECTOR, 'h2.text-center')
    content_iframe_loc = (By.CSS_SELECTOR, "#innocomFrame")
    # # # # # # # # 联系人信息
    con_name_loc = (By.NAME, 'userInfo.contName')
    con_mobile_loc = (By.NAME, 'userInfo.contMobile')
    con_telephone_loc = (By.NAME, 'userInfo.contTel')
    con_fax_loc = (By.NAME, 'userInfo.contFax')
    con_email_loc = (By.NAME, 'userInfo.contEmail')
    # # # # # # # #  企业法人信息
    cor_mobile_loc = (By.NAME, 'userInfo.corMobile')
    cor_telphone_loc = (By.NAME, 'userInfo.corTel')
    cor_fax_loc = (By.NAME, 'userInfo.corFax')
    cor_email = (By.NAME, 'userInfo.corEmail')
    # # # # # #  企业信息
    com_address_loc = (By.NAME, 'userInfo.postalcode')
    com_postalcode_loc = (By.NAME, 'userInfo.postalcode')
    # 企业规模
    com_sale_loc = (By.NAME, 'userInfo.saleIncome')
    # 领域 domain
    com_domain1_loc = (By.CSS_SELECTOR, 'select#onemain')
    com_domain2_loc = (By.CSS_SELECTOR, 'select#scdmain')
    com_domain3_loc = (By.CSS_SELECTOR, 'select#thdmain')
    ###### 已上市按钮
    is_listing_loc = (By.CSS_SELECTOR, 'input#marketStatus1')
    ###### 未上市按钮
    not_listing_loc = (By.CSS_SELECTOR, 'input#marketStatus0')
    ######## 已上市公司信息
    listed_type_loc = (By.NAME, 'userInfo.listedType')
    listed_date_js_str = f"document.getElementById('marketDate').removeAttribute('readonly')"
    listed_date_loc = (By.CSS_SELECTOR, 'input#marketDate')
    # 股票代码
    stock_code_loc = (By.CSS_SELECTOR, 'input#marketCode')
    ###### 企业经营范围和企业简介
    com_operation_loc = (By.NAME, 'userInfo.operation')
    com_desc_loc = (By.NAME, 'userInfo.companyProfile')
    # # 保存按钮
    save_btn_loc = (By.CSS_SELECTOR, 'button#submitBtnId')

    def __init__(self, driver=None, perfect=False):
        self.driver = driver
        self.perfect = perfect

    def __call__(self, *args, **kwargs):
        print("args", args)
        print("kwargs", kwargs)
    @property
    def class_name(self):
        return self.__class__.__name__

    def input_con_info(self, name, mobile, telephone, fax, email):
        BM.input(driver=self.driver, ele_loc=self.con_name_loc, keys=name)
        BM.input(driver=self.driver, ele_loc=self.con_mobile_loc, keys=mobile)
        BM.input(driver=self.driver, ele_loc=self.con_telephone_loc, keys=telephone)
        BM.input(driver=self.driver, ele_loc=self.con_fax_loc, keys=fax)
        BM.input(driver=self.driver, ele_loc=self.con_email_loc, keys=email)

    def input_legal_info(self, mobile, telephone, fax, email):
        BM.input(driver=self.driver, ele_loc=self.cor_mobile_loc, keys=mobile)
        BM.input(driver=self.driver, ele_loc=self.cor_telphone_loc, keys=telephone)
        BM.input(driver=self.driver, ele_loc=self.cor_fax_loc, keys=fax)
        BM.input(driver=self.driver, ele_loc=self.cor_email, keys=email)

    @classmethod
    def get_domain_by_namelist(cls, hitech_field_namelist=""):
        return hitech_field_namelist.split(",")

    def input_com_info(self, address='', postalcode='', com_sale='', domain=''):
        BM.input(driver=self.driver, ele_loc=self.com_address_loc, keys=address)
        BM.input(driver=self.driver, ele_loc=self.com_postalcode_loc, keys=postalcode)
        # # # # # # 企业规模选择
        BM.select_value_choice(selector_loc=self.com_sale_loc, text_value=com_sale, driver=self.driver)
        # # # # # # 领域选择
        domain_num = len(domain.split(","))
        domain1, domain2, domain3, domain4 = None, None, None, None
        if domain_num == 2:
            domain1, domain2 = self.get_domain_by_namelist(hitech_field_namelist=domain)
            domain3 = "无"
            domain += ",无"
        if domain_num == 3:
            domain1, domain2, domain3 = self.get_domain_by_namelist(hitech_field_namelist=domain)
        elif domain_num == 4:
            domain1, domain2, domain3, domain4 = self.get_domain_by_namelist(hitech_field_namelist=domain)

        BM.select_domain(selector_loc=self.com_domain1_loc, text_value=domain1, driver=self.driver, tech_fieldname=domain)
        BM.select_domain(selector_loc=self.com_domain2_loc, text_value=domain2, driver=self.driver, tech_fieldname=domain)
        BM.select_domain(selector_loc=self.com_domain3_loc, text_value=domain3, driver=self.driver, tech_fieldname=domain)

    def click_radio_listing(self, is_listing=None):
        if is_listing: BM.click(driver=self.driver, ele_loc=self.is_listing_loc)
        else: BM.click(driver=self.driver, ele_loc=self.not_listing_loc)

    def input_listed_com_info(self, listed_type='', listed_date='', stock_code=''):
        BM.select_value_choice(selector_loc=self.listed_type_loc, text_value=listed_type, driver=self.driver)

        self.driver.execute_script(self.listed_date_js_str)
        BM.input(driver=self.driver, ele_loc=self.listed_date_loc, keys=listed_date)
        BM.input(driver=self.driver, ele_loc=self.stock_code_loc, keys=stock_code)

    def input_desc_info(self, operation_info='', com_desc=''):
        BM.input(driver=self.driver, ele_loc=self.com_operation_loc, keys=operation_info)
        if not self.perfect:
            BM.input(driver=self.driver, ele_loc=self.com_desc_loc, keys=com_desc)

    def click_save_btn(self):
        BM.global_click_btn(btn_loc=self.save_btn_loc, driver=self.driver)

    @FormDataDecorator
    def main(self, esdate="", contact='', contact_phone='', contact_tel='', contact_fax='',contact_email='',legal_phone='', legal_tel='', legal_fax='', legal_email='',dom='', postalcode='', scale='',hitech_field_namelist='', hitech_field_idlist="", gopublic="", stockcat='', gopublictime='', stockcode='',opscope='；', entbrief_intro=''):
        # 新能源与节能,高效节能技术,高温热泵技术
        # self.flag = False
        g.esdate = esdate
        # if BM.isElementExist(element=self.form_btn_loc, driver=self.driver):
        if not self.perfect:
            BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
            BM.cut_over_frame(driver=self.driver, selector_loc=self.content_iframe_loc)
            BM.wait(driver=self.driver, ele_loc=self.title_loc)

        self.input_con_info(name=contact, mobile=contact_phone, telephone=contact_tel, fax=contact_fax, email=contact_email)
        self.input_legal_info(mobile=contact_phone if not legal_phone else legal_phone,
                              telephone=contact_tel if not legal_tel else legal_tel,
                              fax=contact_fax if not legal_fax else legal_fax,
                              email=contact_email if not legal_email else legal_email)
        if hitech_field_namelist is None:
            hitech_fields = DbTools.get_hitech_name_by_ids(ids=hitech_field_idlist)
            hitech_ = {i.get("id"): i.get("name") for i in hitech_fields}
            hitech_field_namelist = ",".join([hitech_.get(int(i)) for i in hitech_field_idlist.split(",")])
        self.input_com_info(address=dom, postalcode=postalcode, com_sale=scale, domain=hitech_field_namelist)
        self.click_radio_listing(is_listing=gopublic)
        # # # 如果上市了，就选择关于上市公司的信息。
        if gopublic:
            self.input_listed_com_info(listed_type=stockcat, listed_date=gopublictime, stock_code=stockcode)

        # # # #    填写股权结构信息， 当数据查询模块写出来时候，先查询数据，在调用实例的方法。
        WriteCivilType(driver=self.driver).write_civil_type()
        WriteLegalType(driver=self.driver).write_legal_type()
        WriteVentureInvestment(driver=self.driver).write_venture_investment()

        self.input_desc_info(operation_info=opscope, com_desc=entbrief_intro)
        self.click_save_btn()

    @FormDataDecorator
    def write(self, esdate="", contact='', contact_phone='', contact_tel='', contact_fax='',contact_email='',legal_phone='', legal_tel='', legal_fax='', legal_email='',dom='', postalcode='', scale='',hitech_field_namelist='', hitech_field_idlist="", gopublic="", stockcat='', gopublictime='', stockcode='',opscope='；', entbrief_intro=''):
        # 注册登记表链接
        url = "https://slb.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/saveRegLoginInfo.do"
        if self.perfect:
            # 基本信息链接
            url = "https://slb.chinatorch.org.cn/xonlinereport/inforeport/EntInfoChange/saveRegDataForUpdate.do"
        data = {
            "struts.token.name": "token",
            # 这个 token 需要在页面上获取
            "token": "A9PP8YY9JH8IUZLV3Q9YZZLO4XFEZV15",
            "userInfo.contName": contact,
            "userInfo.contMobile": contact_phone,
            "userInfo.contTel": contact_tel if contact_tel else "",
            "userInfo.contFax": contact_fax if contact_fax else "",
            "userInfo.contEmail": contact_email,
            "userInfo.corMobile": legal_phone,
            "userInfo.corTel": legal_tel if legal_tel else "",
            "userInfo.corFax": legal_fax if legal_fax else "",
            "userInfo.corEmail": legal_email,
            "userInfo.address": dom,
            "userInfo.postalcode": postalcode,
            "userInfo.saleIncome": str(saleIncome.get(scale)),
            # 根据 hitech_field_namelist 获取 国网技术领域对应value
            # gopublic 为 1 时 增加这些数据
            # 这些在另三个 class 中获取数据
            # 这个字段在 注册登记表中有 但在 企业基本信息修改中没有
        }
        # 获取技术领域信息
        domain_dict = hzflowOperation.get_domain_by_namelist(hitech_field_namelist=hitech_field_namelist)
        data.update(domain_dict)
        data["userInfo.marketStatus"] = gopublic
        if gopublic == 1:
            data["userInfo.listedType"] = str(listedType.get(stockcat))
            data["userInfo.marketDate"] = gopublictime
            data["userInfo.marketCode"] = stockcode if stockcode else ""
        # 获取股权结构和风险投资信息
        legal = []
        legal.extend(WriteCivilType(driver=self.driver).write())
        legal.extend(WriteLegalType(driver=self.driver).write())
        legal.extend(WriteVentureInvestment(driver=self.driver).write())
        for i, item in enumerate(legal):
            data["entEquityList[{}].personType".format(i)] = item.get("type")
            data["entEquityList[{}].personName".format(i)] = item.get("name")
            data["entEquityList[{}].idCode".format(i)] = item.get("id_num")
            data["entEquityList[{}].touzi".format(i)] = item.get("invest")
        data["userInfo.operation"] = opscope
        if self.perfect:
            data["userInfo.companyProfile"] = entbrief_intro
        data["hide"] = ""
        # userInfo.id 也需要从页面中获取
        data["userInfo.id"] = "2020050916115411340"

